package com.incar.chuxing.activity.personal;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.incar.chuxing.R;
import com.incar.chuxing.adapter.TravelRecordAdapter;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.TravelRecordBean;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.LoadSirCallback.EmptyCallback;
import com.incar.chuxing.utils.LoadSirCallback.NetErrorCallback;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.widget.CustomLoadMoreView;
import com.kingja.loadsir.core.LoadSir;
import com.kingja.loadsir.core.Transport;

import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TravelRecordActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {


    private static final int PAGE_SIZE = 8;
    @BindView(R.id.rc_personal)
    RecyclerView rcTravel;
    @BindView(R.id.sr_personal)
    SwipeRefreshLayout srPersonal;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout mCollapsingToolbarLayout;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    private Context mContext = this;
    private TravelRecordAdapter travelRecordAdapter;
    private int curPage = 1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_my_route;
    }

    @Override
    public void initView() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getAppManager().finishActivity();
            }
        });
        //设置加载异常的处理
        loadService = LoadSir.getDefault().register(srPersonal, new com.kingja.loadsir.callback.Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                //主动转圈并加载
                srPersonal.setOnRefreshListener(TravelRecordActivity.this);
                srPersonal.setColorSchemeColors(Color.rgb(82, 186, 254));
                rcTravel.setLayoutManager(new LinearLayoutManager(mContext));
                srPersonal.setRefreshing(true);
                onRefresh();
            }
        });
        loadService.setCallBack(EmptyCallback.class, new Transport() {
            @Override
            public void order(Context context, View view) {
                TextView mTvEmpty = (TextView) view.findViewById(R.id.no_data_tv);
                mTvEmpty.setText("您还没有订单哦！");
            }
        });

        initAdapter();
        srPersonal.setOnRefreshListener(this);
        srPersonal.setColorSchemeColors(Color.rgb(82, 186, 254));
        rcTravel.setLayoutManager(new LinearLayoutManager(mContext));
        srPersonal.setRefreshing(true);
        onRefresh();
    }

    private void initAdapter() {
        travelRecordAdapter = new TravelRecordAdapter();
        travelRecordAdapter.setOnLoadMoreListener(this, rcTravel);
        travelRecordAdapter.setPreLoadNumber(1);
        travelRecordAdapter.setLoadMoreView(new CustomLoadMoreView());
        rcTravel.setAdapter(travelRecordAdapter);
        rcTravel.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转订单详情
                Intent intent = new Intent(mContext, TravelDetailActivity.class);
                intent.putExtra("orderId", travelRecordAdapter.getItem(position).getId());
                startActivity(intent);
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    /*@OnClick({ R.id.title_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
        }

    }
*/
    @Override
    public void onRefresh() {
        loadService.showSuccess();
        curPage = 1;
        travelRecordAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getTravelRecord(((MyApplication) getApplication()).getRequestFieldMap(), curPage + "", PAGE_SIZE + "", "1")
                .enqueue(new Callback<TravelRecordBean>() {
                    @Override
                    public void onResponse(Call<TravelRecordBean> call, Response<TravelRecordBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                if (null != response.body().getAttachment() && null != response.body().getAttachment().getCompleteOrderlList() && !response.body().getAttachment().getCompleteOrderlList().isEmpty()) {
                                    setData(true, response.body().getAttachment().getCompleteOrderlList());
                                } else {
                                    loadService.showCallback(EmptyCallback.class);
                                }
                                if (srPersonal != null) {
                                    travelRecordAdapter.setEnableLoadMore(true);
                                    srPersonal.setRefreshing(false);
                                }
                            } else if (response.body().getStatus() == 20) {
                                ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<TravelRecordBean> call, Throwable t) {
                        loadService.showCallback(NetErrorCallback.class);
                        if (srPersonal != null) {
                            travelRecordAdapter.setEnableLoadMore(true);
                            srPersonal.setRefreshing(false);
                        }
                    }
                });
    }

    @Override
    public void onLoadMoreRequested() {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getTravelRecord(((MyApplication) getApplication()).getRequestFieldMap(), curPage + "", PAGE_SIZE + "", "1")
                .enqueue(new Callback<TravelRecordBean>() {
                    @Override
                    public void onResponse(Call<TravelRecordBean> call, Response<TravelRecordBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                setData(false, response.body().getAttachment().getCompleteOrderlList());
                            } else if (response.body().getStatus() == 20) {
                                ToastUtils.makeText(mContext, "请重新登录", ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                startActivity(intent);
                                AppManager.getAppManager().finishAllActivity();
                            } else {
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<TravelRecordBean> call, Throwable t) {
                        travelRecordAdapter.loadMoreFail();
                    }
                });
    }


    private void setData(boolean isRefresh, List data) {
        curPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            travelRecordAdapter.setNewData(data);
        } else {
            if (size > 0) {
                travelRecordAdapter.addData(data);
            }
        }

        if (size < PAGE_SIZE) {
            //第一页不够一页就不显示没有更多数据
            travelRecordAdapter.loadMoreEnd(isRefresh);
        } else {
            travelRecordAdapter.loadMoreComplete();
        }
    }

}
